package com.chuanjiabao.wisdom.listener;

import android.arch.lifecycle.MutableLiveData;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class NetworkCallbackImpl extends ConnectivityManager.NetworkCallback {

    public static MutableLiveData<String> networkState = new MutableLiveData<>();

    @Override
    public void onAvailable(Network network) {
        super.onAvailable(network);
        networkState.postValue("connected");
        Log.e("NetworkCallback", "网络连接了");
    }

    @Override
    public void onLost(Network network) {
        super.onLost(network);
        networkState.postValue("disconnected");
        Log.e("NetworkCallback", "网络断开了");
    }

    @Override
    public void onCapabilitiesChanged(Network network, NetworkCapabilities networkCapabilities) {
        super.onCapabilitiesChanged(network, networkCapabilities);
        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
            if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                networkState.postValue("wifi");
                Log.e("NetworkCallback", "wifi网络已连接");
            } else {
                networkState.postValue("mobile");
                Log.e("NetworkCallback", "移动网络已连接");
            }
        }
    }

}
